<!--
    by: yuanbiao 2020年11月25日
    name: x-drawboard
    notes:
-->
<template>
  <div :class="[
    prefixCls,
    `${prefixCls}-${type}`,
    `${prefixCls}-${mode}`,
    multiple ? `${prefixCls}-multiple` : `${prefixCls}-single`,
    `${prefixCls}-${placement}`,
    `${prefixCls}-${size}`
  ]">
    <div :class="`${prefixCls}__control`"
      @mousedown="toggleHandler" @touchstart="toggleHandler"
      @mouseenter="toggleToolsbar(true)" @touchenter="toggleToolsbar(true)"
      @mouseleave="toggleToolsbar(false)" @touchleave="toggleToolsbar(false)"
    >
      <slot name="toggle">
        <i class="xvu-iconfont xvu-pen"></i>
      </slot>
      <transition enter-active-class="animated fadeIn" leave-active-class="animated fadeOut">
        <div v-if="active && showToolsbar" :class="[`${prefixCls}__toolsbar`, 'clearfix']" @mousedown.stop @touchstart.stop>
          <div :class="[`${prefixCls}__toolsbar_item`, 'clearfix']" v-for="(v,i) in toolsbarData" :key="i">
            <span :class="`${prefixCls}__toolsbar_label`">{{v.label}}</span>
            <span v-for="(item,index) in v.list" :key="`${i}_${index}`"
              :class="[`${prefixCls}__toolsbar_btn`, {
                active: !item.immediate && (_self[`${v.name}ActiveIndex`] === index)
              }]"
              @mousedown.stop="btnClickHandler(i, index)"
              @touchstart.stop="btnClickHandler(i, index)"
              :title="item.label"
            >
              <i v-if="v.name==='size'"
                :class="[`${prefixCls}__toolsbar_btn_size`]"
                :style="{width: `${item.value}px`, height: `${item.value}px`}"
              ></i>
              <i v-else-if="['shape', 'operate'].includes(v.name)"
                :class="[`${prefixCls}__toolsbar_btn_shape`, item.icon]"
              ></i>
              <i v-else-if="v.name==='color'"
                :class="[`${prefixCls}__toolsbar_btn_color`]"
                :style="{backgroundColor: item.color}"
              ></i>
            </span>
          </div>
          <div :class="[`${prefixCls}__toolsbar_arrow`]"></div>
        </div>
      </transition>
    </div>
  </div>
</template>

<script>
import { debounce } from '@/script/utils.js'
import Canvas from './canvas'
const prefixCls = 'x-drawboard'
export default {
  name: 'x-drawboard',
  props: {
    type: {
      type: String,
      default: 'default' // default|primary|info|success|warning|danger|brown
    },
    size: {
      type: String,
      default: 'default' // default|large|small
    },
    mode: {
      type: String,
      default: 'horizontal' // horizontal|vertical
    },
    multiple: {
      type: Boolean,
      default: false
    },
    placement: {
      type: String,
      default: 'top' // 工具条位置 top|bottom|left|right
    },
    targetNode: {
      type: Object,
      default: null // canvas要放入的目标DOM元素对象
    },
    targetElement: {
      type: String,
      default: 'body' // canvas要放入的目标元素选择器
    }
  },
  data() {
    return {
      prefixCls: prefixCls,
      canvas: null,
      timer: null,
      active: false,
      showToolsbar: false,
      sizeActiveIndex: 0,
      shapeActiveIndex: 3,
      colorActiveIndex: 0,
      operateActiveIndex: -1,
      toolsbarData: [
        {name: 'size', label: '粗 细', list: [
          {name: 'xs', label: '极小', value: 2},
          {name: 'sm', label: '小', value: 6},
          {name: 'md', label: '中', value: 10},
          {name: 'lg', label: '大', value: 14}
        ]},
        {name: 'shape', label: '形 制', list: [
          {name: 'square', label: '方形', icon: 'xvu-iconfont xvu-rect'},
          {name: 'circle', label: '圆形', icon: 'xvu-iconfont xvu-circle'},
          {name: 'straight', label: '直线', icon: 'xvu-iconfont xvu-line'},
          {name: 'wave', label: '波浪', icon: 'xvu-iconfont xvu-wave'},
          {name: 'arrow', label: '箭头', icon: 'xvu-iconfont xvu-linearrow-right'}
        ]},
        {name: 'color', label: '颜 色', list: [
          {name: 'red', label: '红色', color: '#FF3F3F'},
          {name: 'purple', label: '紫色', color: '#9743FF'},
          {name: 'blue', label: '蓝色', color: '#5171F5'},
          {name: 'yellow', label: '黄色', color: '#FFA622'},
          {name: 'black', label: '黑色', color: '#333333'}
        ]},
        {name: 'operate', label: '操 作', list: [
          {name: 'eraser', label: '橡皮擦', icon: 'xvu-iconfont xvu-eraser'},
          {name: 'cancel', label: '返回上一步', icon: 'xvu-iconfont xvu-cancel', immediate: true},
          {name: 'clear', label: '清空画布', icon: 'xvu-iconfont xvu-delete', immediate: true}
        ]}
      ]
    }
  },
  computed: {
    penConfigActive () {
      let result = {}
      this.toolsbarData.forEach(v => {
        if (v.name === 'size') result.thickness = (v.list[this.sizeActiveIndex] || {}).value
        else if (v.name === 'shape') result.shape = (v.list[this.shapeActiveIndex] || {}).name
        else if (v.name === 'color') result.color = (v.list[this.colorActiveIndex] || {}).color
      })
      return result
    }
  },
  watch: {
    active (n, o) {
      console.log(`active变化：${o}=>${n}`)
      if (n) {
        this.canvas = new Canvas({
          ...this.penConfigActive,
          role: 'pen',
          parentNode: this.targetNode,
          parentSelector: this.targetElement
        })
        this.operateActiveIndex = -1
        // 设置canvas可用状态
        this.canvas.useable = n
      } else {
        this.canvas && this.canvas.destroy()
      }
    }
  },
  methods: {
    // 开启/关闭画笔功能
    toggleHandler: debounce(function () {
      this.active = !this.active
      this.showToolsbar = true
    }, 200),
    toggleToolsbar: debounce(function (flag) {
      clearTimeout(this.timer)
      if (flag) {
        this.showToolsbar = flag
      } else {
        this.timer = setTimeout(() => {
          this.showToolsbar = false
        }, 1000)
      }
    }, 200),
    // 按钮事件处理
    btnClickHandler: debounce(function (index, childIndex) {
      this.canvas.role = 'pen'
      this.operateActiveIndex = -1
      let itemActive = this.toolsbarData[index] || {}
      let childActive = (itemActive.list || [])[childIndex] || {}
      this[`${itemActive.name}ActiveIndex`] = childIndex
      if (itemActive.name === 'size') this.setPenSize(childActive)
      else if (itemActive.name === 'shape') this.setPenShape(childActive)
      else if (itemActive.name === 'color') this.setPenColor(childActive)
      else if (itemActive.name === 'operate') this.operateHandler(childActive)
    }, 200),
    // 按钮事件处理/size
    setPenSize (data) {
      this.canvas.thickness = data.value
    },
    // 按钮事件处理/shape
    setPenShape (data) {
      this.canvas.shape = data.name
    },
    // 按钮事件处理/color
    setPenColor (data) {
      this.canvas.color = data.color
    },
    // 按钮事件处理/operate
    operateHandler (data) {
      if (data.name === 'cancel') this.canvas.restoreImageData(true)
      else if (data.name === 'clear') this.canvas.clearCanvas()
      else if (data.name === 'eraser') this.canvas.role = 'eraser'
    },
    // 方法/resize
    resize () {
      this.canvas && this.canvas.autoResizeCanvas()
    }
  }
}
</script>
